angular.module('driver')
	.factory('Path', ['$localstorage', function($localstorage) {
		var o = {
			array: [],//路径
			length : 0,//
			uploaded: false,
			calcFlag: 0,
			started: false,
			accuracy: 100,//精度
			timeout: 15 * 1000,
			logTime: 0,
		};

		var EARTH_RADIUS = 6378.137;
		var TEN = 10;

		function rad(d)
		{
		   return d * Math.PI / 180.0;
		};

		function GetDistance(lat1, lng1, lat2, lng2)
		{
		   var radLat1 = rad(lat1);
		   var radLat2 = rad(lat2);
		   var a = radLat1 - radLat2;
		   var b = rad(lng1) - rad(lng2);
		   var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + 
		    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
		   s = s * EARTH_RADIUS;
		   s = Math.round(s * 10000) / 10000;
		   return s;
		};

		o.initialPath = function () {
			o.array = [];
			o.length = 0;
			o.calcFlag = 0;
			o.started = true;
		};
		o.stop = function () {
			o.started = false;
		};

		o.addPosition = function (position) {
			if (position.accuracy > o.accuracy)
				return;

			var now = Date.now();
			if( now - o.logTime < o.timeout )
				return;
			o.logTime = now;

			if (!o.started)
				return;
			
			o.array.push( position.position );
		};

		o.calcDistance = function () {
			if (o.array.length < 2)
				return;

			for (var i = o.calcFlag; i < o.array.length; i++) {
				o.length += GetDistance(o.array[i].lat, o.array[i].lng, o.array[i+1].lat, o.array[i+1].lng);
			};

			o.calcFlag = o.array.length;

			return o.length;
		};

		o.getLength = function () {
			if (o.length !== o.array.length)
				o.calcDistance();

			return o.length;
		};


		return o;
	}]);
